package com.ruoyi.project.app.util;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

public class CalculationUtil {
    /**
     * date2比date1多的天数
     *
     * @param date1 Date
     * @param date2 Date
     * @return day
     */
    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        //是否同一年
        if (year1 != year2) {
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                //是否闰年
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                    timeDistance += 366;
                } else {
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2 - day1);
        } else {
            return day2 - day1;
        }
    }

    /**
     * 处理金钱之差
     *
     * @param passive 被减数
     * @param active  减数
     * @param scale   保留位数
     * @return 差
     */
    public static String handleSubStr(String passive, String active, int scale) {
        if (passive == null || "".equals(passive)) passive = "0";
        if (active == null || "".equals(active)) return passive;
        BigDecimal decimalP = new BigDecimal(passive);
        BigDecimal decimalA = new BigDecimal(active);
        BigDecimal decimal = decimalP.subtract(decimalA);
        return decimal.setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
    }

    /**
     * 处理金钱之积
     *
     * @param passive 被
     * @param active  主
     * @param scale   保留位数
     * @return 积
     */
    public static String handleMulStr(String passive, String active, int scale) {
        if (passive == null || "".equals(passive)) passive = "0";
        if (active == null || "".equals(active)) return passive;
        BigDecimal decimalAu = new BigDecimal(passive);
        BigDecimal decimalAd = new BigDecimal(active);
        BigDecimal decimal = decimalAu.multiply(decimalAd);
        return decimal.setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
    }


    /**
     * 处理金钱之和
     *
     * @param passive 被加数
     * @param active  加数
     * @param scale   保留位数
     * @return 差
     */
    public static String handleAddStr(String passive, String active, int scale) {
        if (passive == null || "".equals(passive)) passive = "0";
        if (active == null || "".equals(active)) return passive;
        BigDecimal decimalP = new BigDecimal(passive);
        BigDecimal decimalA = new BigDecimal(active);
        BigDecimal decimal = decimalP.add(decimalA);
        return decimal.setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
    }

}
